package xyz.yuzegod.megawalls.command;

import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import xyz.yuzegod.megawalls.MegaWalls;

import java.util.ArrayList;
import java.util.List;

public class CommandHandler implements CommandExecutor, TabCompleter
{
    private List<BaseCommand> commands;
    
    public CommandHandler() {
        this.commands = new ArrayList<BaseCommand>();
        this.registerCommand(MegaWalls.getInstance(), new CommandStage());
        this.registerCommand(MegaWalls.getInstance(), new CommandKill());
        this.registerCommand(MegaWalls.getInstance(), new CommandSurface());
        this.registerCommand(MegaWalls.getInstance(), new CommandMaster());
        this.registerCommand(MegaWalls.getInstance(), new CommandCoins());
        this.registerCommand(MegaWalls.getInstance(), new CommandDust());
        this.registerCommand(MegaWalls.getInstance(), new CommandParty());
        this.registerCommand(MegaWalls.getInstance(), new CommandWalls());
        this.registerCommand(MegaWalls.getInstance(), new CommandForceStart());
        this.registerCommand(MegaWalls.getInstance(), new ShoutCommand());
    }
    
    public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
        for (final BaseCommand command : this.commands) {
            if (command.isValidTrigger(cmd.getName())) {
                if (!command.hasPermission(sender)) {
                    sender.sendMessage("§c你没有此命令的权限！");
                    return true;
                }
                if (command.isOnlyPlayerExecutable() && !(sender instanceof Player)) {
                    sender.sendMessage("§c控制台无法使用此命令！");
                    return true;
                }
                if (args.length >= command.getMinimumArguments()) {
                    try {
                        command.execute(sender, label, args);
                        return true;
                    }
                    catch (CommandException ex) {
                        continue;
                    }
                }
                sender.sendMessage("§c错误的参数: /" + command.getName() + " " + command.getPossibleArguments());
            }
        }
        return false;
    }
    
    public List<String> onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) {
        return null;
    }
    
    public void registerCommand(final JavaPlugin plugin, final BaseCommand command) {
        this.commands.add(command);
        plugin.getCommand(command.getName()).setExecutor((CommandExecutor)this);
        plugin.getCommand(command.getName()).setTabCompleter((TabCompleter)this);
    }
}
